﻿// Copyright © 2011 Paul Vanukoff (pvanukoff@gmail.com)

namespace Bravura.Native.PluginBase
{
	/// <summary>
	/// A sample buffer which supports linear interpolation.
	/// </summary>
	public class SampleBuffer
	{
		protected int _length = 0;
		protected double[] _data = null;

		#region Methods

		/// <summary>
		/// Gets sample buffer length.
		/// </summary>
		public double GetLength()
		{
			return _length;
		}

		/// <summary>
		/// Loads sample buffer data.
		/// </summary>
		public void Load(double[] input)
		{
			_length = input.Length;
			_data = new double[_length + 1];

			// load buffer
			for (int i = 0; i < _length; i++)
			{
				_data[i] = input[i];
			}

			// copy first sample into last position to support interpolation of the last sample
			_data[_length] = input[0];
		}

		/// <summary>
		/// Gets a non-interpolated value.
		/// </summary>
		public double GetValue(int pos)
		{
			return _data[pos];
		}

		/// <summary>
		/// Gets an interpolated value.
		/// </summary>
		public double GetValue(double realPos)
		{
			int intPos = (int)realPos;
			double val0 = _data[intPos];
			double val1 = _data[intPos + 1];
			double mix = realPos - intPos;
			return mix * val1 + (1.0 - mix) * val0;
		}

		#endregion
	}
}
